package com.zjh.admin.sys.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjh.admin.sys.model.RoleEntity;
import com.zjh.admin.sys.model.UserEntity;
import com.zjh.admin.sys.model.UserInfoEntity;
import com.zjh.admin.sys.service.RoleService;
import com.zjh.admin.sys.service.UserService;
import com.zjh.common.constants.Common;
import com.zjh.common.dtgrid.model.Pager;
import com.zjh.common.dtgrid.util.ExportUtils;
import com.zjh.common.result.Result;
import com.zjh.common.util.PageUtil;
import com.zjh.core.base.basecontroller.BaseController;
import com.zjh.core.exception.AjaxException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author ZWX
 * @Description: 资源controller
 * @date 2018/10/15 23：28
 */
@Controller
@RequestMapping("/user/")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * list跳转
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("listUI.html")
    public String listUI(Model model, HttpServletRequest request) {
        try {
            PageUtil page = new PageUtil();
            if (request.getParameterMap().containsKey("page")) {
                setPage(request, page);
            }
            model.addAttribute("page", page);
            return Common.BACKGROUND_PATH + "/sys/user/list";
        } catch (Exception e) {
            throw new AjaxException(e);
        }
    }


    /**
     * ajax分页动态加载模式
     *
     * @param gridPager
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/list.html")
    @ResponseBody
    public Object list(String gridPager, HttpServletResponse response) throws Exception {
        //1、映射Pager对象
        Pager pager = JSON.parseObject(gridPager, Pager.class);
        //2、设置查询参数
        Map<String, Object> parameters = pager.getParameters();
        parameters.put("fastQueryMap", getFastqueryParameters(pager.getFastQueryParameters()));

        //3、判断是否是导出操作
        if (pager.getIsExport()) {
            if (pager.getExportAllData()) {
                //3.1、导出全部数据
                List<UserEntity> list = userService.queryListByPage(parameters);
                ExportUtils.exportAll(response, pager, list);
                return null;
            } else {
                //3.2、导出当前页数据
                ExportUtils.export(response, pager);
                return null;
            }

        } else {
            //设置分页，page里面包含了分页信息
            Page<Object> page = PageHelper.startPage(pager.getNowPage(), pager.getPageSize(), true);
            List<UserEntity> list = userService.queryListByPage(parameters);
            parameters.clear();
            setPageList(parameters, pager, page, list);
            return parameters;
        }
    }

    /**
     * add跳转
     *
     * @param model
     * @return
     */
    @RequestMapping("addUI.html")
    public String addUI(Model model) {
        try {
            List<RoleEntity> list = roleService.queryListByPage(new HashMap<>(16));
            model.addAttribute("roleList", list);
            return Common.BACKGROUND_PATH + "/sys/user/form";

        } catch (Exception e) {
            throw new AjaxException(e);
        }

    }

    /**
     * 添加用户信息
     *
     * @param userEntity
     * @return
     * @throws AjaxException
     */
    @RequestMapping("add.html")
    @ResponseBody
    public Object add(UserEntity userEntity) throws AjaxException {
        Result result = new Result();
        try {
            //设置创建者姓名
            userEntity.setCreatorName("1023589809@qq.com");
            userEntity.setCreateTime(new Date(System.currentTimeMillis()));
            //设置锁定状态：未锁定；删除状态：未删除
            userEntity.setLocked(0);
            userEntity.setDeleteStatus(0);
            UserInfoEntity userInfo = new UserInfoEntity();
            userEntity.setUserInfo(userInfo);

            int status = userService.insert(userEntity);
            if (status == 1) {
                result.success("添加成功");
            } else {
                result.error("添加失败");
            }

        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * edit跳转
     *
     * @param model
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("editUI.html")
    public String editUI(Model model, HttpServletRequest request, Long id) {
        try {
            UserEntity userEntity = userService.findById(id);

            PageUtil page = new PageUtil();
            setPage(request, page);

            List<RoleEntity> list = roleService.queryListByPage(new HashMap<>(16));

            model.addAttribute("page", page);
            model.addAttribute("userEntity", userEntity);
            model.addAttribute("roleList", list);
            return Common.BACKGROUND_PATH + "/sys/user/form";
        } catch (Exception e) {
            throw new AjaxException(e);
        }
    }

    /**
     * 修改用户信息
     *
     * @param userEntity
     * @return
     * @throws AjaxException
     */
    @RequestMapping("edit.html")
    @ResponseBody
    public Object update(UserEntity userEntity) throws AjaxException {
        Result result = new Result();
        try {
            //设置创建者姓名
            userEntity.setCreatorName("1023589809@qq.com");
            int status = userService.update(userEntity);
            if (status == 1) {
                result.success("编辑成功");
            } else {
                result.error("编辑失败");
            }

        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * 校验 用户名称是否存在
     *
     * @param accountName
     * @return
     */
    @RequestMapping("withoutAuth/validateAccountName.html")
    @ResponseBody
    public Object validateAccount(String accountName) {
        try {
            UserEntity userEntity = userService.findByName(accountName);
            return userEntity == null;

        } catch (Exception e) {
            throw new AjaxException(e);
        }
    }

    /**
     * 密码重置
     *
     * @param userEntity
     * @return
     */
    @RequestMapping("resetPassword.html")
    @ResponseBody
    public Object resetPassword(UserEntity userEntity) {
        Result result = new Result();
        try {
            userEntity.setPassword("123456");
            if (userEntity.getId() == null) {
                UserEntity user = userService.findByName(userEntity.getAccountName());
                if (user != null) {
                    userEntity.setId(user.getId());
                    userEntity.setUserName(user.getUserName());
                    int cnt = userService.updatePassword(userEntity);
                    if (cnt > 0) {
                        result.success("密码重置成功");
                    } else {
                        result.error("密码重置失败");
                    }
                } else {
                    result.error("密码重置失败");
                }

            } else {
                int cnt = userService.updatePassword(userEntity);
                if (cnt > 0) {
                    result.success("密码重置成功");
                } else {
                    result.error("密码重置失败");
                }
            }

        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * 删除用户信息
     *
     * @param ids
     * @return
     */
    @RequestMapping("deleteBatch.html")
    @ResponseBody
    public Object deleteBatch(String ids) {
        Result result = new Result();
        try {
            String[] userIds = ids.split(",");
            List<Long> list = new ArrayList<>();
            for (String string : userIds) {
                list.add(Long.valueOf(string));
            }
            int status = userService.deleteBatchById(list);
            if (status == list.size()) {
                result.success("删除成功");
            } else {
                result.error("删除失败");
            }
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }


}
